package com.scau.classOnline.controller;

import com.scau.classOnline.dto.ScheduleDTO;
import com.scau.classOnline.dto.ScheduleFileDTO;
import com.scau.classOnline.model.RespEntity;
import com.scau.classOnline.service.ScheduleService;
import com.scau.classOnline.sftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * Create by ji on 2019-07-11
 */
@RestController
@RequestMapping("/api/schedule")
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private FTPClient ftpClient;

    @GetMapping("/get")
    private RespEntity getScheduleById(@RequestParam("id") Integer id) {
        return RespEntity.ok(scheduleService.getScheduleById(id));
    }

    @PostMapping("/add")
    private RespEntity addSchedule(@RequestBody ScheduleDTO scheduleDTO) {
        return RespEntity.ok(scheduleService.addSchedule(scheduleDTO));
    }

    @PostMapping("/update")
    private RespEntity modifyScheduleById(@RequestBody ScheduleDTO scheduleDTO){
        return RespEntity.ok(scheduleService.updateScheduleById(scheduleDTO));
    }

    @PostMapping("/upload")
    private RespEntity uploadCourseWare(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String sid = request.getParameter("sid");
        ScheduleFileDTO scheduleFileDTO = new ScheduleFileDTO();
        scheduleFileDTO.setSid(Integer.valueOf(sid));
        scheduleFileDTO.setName(file.getOriginalFilename());
        scheduleFileDTO.setUrl(getFileUrl(file));
        return RespEntity.ok(scheduleService.uploadCourseWare(scheduleFileDTO));
    }


    private String getFileUrl(MultipartFile file) {
        String courseWarePath = ftpClient.getRemoteCourseWarePath();
        String courseWareRoute = courseWarePath.substring(courseWarePath.lastIndexOf("/"));
        String filename = file.getOriginalFilename();
        filename=System.currentTimeMillis()+filename.substring(filename.lastIndexOf("."));
        ftpClient.upload(file, courseWarePath, filename);
        return "http://" + ftpClient.getHost() + courseWareRoute + "/" + filename;
    }
}
